package cn.jjxx.core.filter.xss;


import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jjxx.core.utils.JeewebPropertiesUtil;
import cn.jjxx.core.utils.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List; 

/**
 * 
*@Title HttpHostFilter.java
*@description TODO
*@time 2021年3月25日 下午1:20:25
*@author YAOXIONG
*@version 1.0
*
 */
@SuppressWarnings("serial")
public class HttpHostFilter  extends HttpServlet implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		StringBuffer url = request.getRequestURL();
		String s = request.getRequestURL().toString();
		// 头攻击检测  过滤主机名
		String requestHost = request.getHeader("host");
		if (requestHost != null && !checkBlankList(requestHost)) {
			response.setStatus(403);
			return;
		}
		filterChain.doFilter(request, response);
	}

//	//判断主机是否存在白名单中
//	private boolean checkBlankList(String host){
//		List<String> list = new ArrayList<String>();
//		list.add("127.0.0.1"); 
//		list.add("localhost");
//		list.add("192.168.20.166");
//		list.add("192.168.20.59");
//		list.add("139.9.227.185");
//		list.add("139.9.154.118");
//		list.add("172.16.0.35");
//		for (String string : list) {
//			if(host.contains(string)){
//				return true;
//			}
//		} 
//		return false;
//	}
	

	//判断主机是否存在白名单中
	private boolean checkBlankList(String host){		
		String ipWhiteList = JeewebPropertiesUtil.getConfig("ip.white.list");
		List<String> list = StringUtils.stringtoList(ipWhiteList, ",");
		for (String string : list) {
			if(host.contains(string)){
				return true;
			}
		} 
		return false;
	}
} 